import { Controller, Get, Post, Put, Del, Inject, Body, Param, Query } from '@midwayjs/decorator';
import { ClassService } from '../../service/firmware/class.service';
import { resBuild } from '@utils/resBuild';
import { StudentWristbandService } from '@service/firmware/student_wristband.service';

@Controller('/class')
export class ClassController {
  @Inject()
  classService: ClassService;
  @Inject()
  studentWristband: StudentWristbandService;

  // 创建班级
  @Post('/create')
  async create(@Body() body) {
    try {
      await this.classService.createClass(body);
      return resBuild.success("新增成功！");
    } catch (error) {
      return resBuild.fail(error.message);
    }
  }

  // 获取所有班级
  @Get('/list')
  async list(@Query() query) {
    console.log('query', query)
    const classes = await this.classService.getAllClasses(query);
    return { success: true, data: classes };
  }

  // 获取单个班级
  @Get('/:id')
  async getById(@Param('id') id: number) {
    try {
      const classEntity = await this.classService.getClassById(id);
      if (!classEntity) return resBuild.fail("班级不存在");
      return resBuild.data(classEntity);
    } catch (err) {
      resBuild.fail(err.message)
    }
  }

  // 更新班级
  @Put('/update/:id')
  async update(@Param('id') id: number, @Body() body) {
    try {
      const updatedClass = await this.classService.updateClass(body);
      if (!updatedClass) return resBuild.fail("更新失败，班级不存在");
      return resBuild.data(updatedClass);
    } catch (error) {
      return resBuild.fail(error.message);
    }
  }

  // 删除班级
  @Del('/delete/:id')
  async delete(@Param('id') id: number) {
    const deleted = await this.classService.deleteClass(id);
    if (!deleted) return { success: false, message: '删除失败，班级不存在' };
    return { success: true, message: '删除成功' };
  }

  // 班级批量给学生分配手环
  @Get('/setStuWb')
  async setStuWb(@Query() params){
    try{
      const result = await this.studentWristband.setStuWb(params)
      return resBuild.success(`分配成功，已成功分配${result.assignedCount}个手环，剩余${result.unassignedCount}个学生未分配`)
    }catch(err){
      // console.log('111',err)
      return resBuild.fail(err.message || '分配手环时发生错误');
    }
  }
}
